<?php
declare(strict_types=1);

namespace app\validate\api\admin\system;

use app\model\api\admin\system\Role;
use app\validate\api\ApiBaseValidate;

class RoleValidate extends ApiBaseValidate
{
    protected $ex_data = [];

    protected $rule = [
        'id' => 'require|integer',
        'title' => 'max:64|isValidTitle',
        'status' => 'in:0,1',
        'rules' => 'require|regex:ids',
        'code' => 'alphaDash|max:32',
        'remark' => 'max:255',
        'parent_id' => 'require|integer|isParentIdValid',
        'sort' => 'integer',
        'dept_id' => 'require|integer|isDeptIdValid',

        // 扩展
        'ids' => 'require|regex:ids',
        'del_ids' => 'require|regex:ids|hasChild',
        'data_scope' => 'require|array:type,custom',
        'data_scope.type' => 'require|in:0,1,2,3,4,5,6',
        'data_scope.custom' => 'array',
    ];

    protected $message = [];

    protected $scene = [
        'save' => ['title', 'status', 'code', 'remark', 'parent_id', 'sort'],
        'update' => ['id', 'title', 'status', 'code', 'remark', 'parent_id', 'sort'],
        'delete' => ['del_ids'],
        'changeDept' => ['ids', 'dept_id'],
        'setDataScope' => ['id', 'parent_id', 'data_scope', 'data_scope.type', 'data_scope.custom'],
        'setRules' => ['id', 'parent_id', 'rules'],
    ];

    protected function hasChild($value, $rule, $data = [])
    {
        $m = Role::where([
            ['parent_id', 'in', $data['del_ids']]
        ])
            ->field('id')
            ->select();

        if (!$m->isEmpty()) {
            return '存在子角色，无法删除';
        }
        return true;
    }

    // 添加父级ID验证方法 
    protected function isParentIdValid($value, $rule, $data = [], $field = '', $title = '')
    {
        // 为了方便处理所有子级,调整为只支持一个根父级,或只有超管才能选择根父级
        if ($value == 0) {
            return is_super_admin() ? true : '请选择一个父级';
        }

        $targetRole = Role::where([
            ['id', '=', $value],
            ['status', '=', Role::STATUS['NOMAL'][0]],
        ])->find();

        if (!$targetRole) {
            return '所选父级不存在或已禁用或无权访问';
        }

        if (isset($data['id']) && $data['id'] != '') {
            // 检查不能选择自己作为父级
            if ($data['id'] == $value) {
                return '不能选择自己作为父级';
            }

            // 检查不能选择自己的子级作为父级
            $currentRole = Role::where('id', $data['id'])->find();
            if ($currentRole) {
                $path = $currentRole->parent_ids ? $currentRole->parent_ids . ',' . $currentRole->id : $currentRole->id;

                if ($targetRole->parent_ids) {
                    $targetPath = $targetRole->parent_ids . ',' . $targetRole->id;
                    if (strpos($targetPath, (string) $path) === 0) {
                        return '不能选择子级作为父级';
                    }
                }
            }
        }

        return true;
    }

    // 添加标题验证方法
    protected function isValidTitle($value, $rule, $data = [], $field = '', $title = '')
    {
        if (isset($data['id']) && $data['id'] != '') {
            $existsSameName = Role::where([
                ['parent_id', '=', $data['parent_id']],
                ['id', '<>', $data['id']],
                ['title', '=', $data['title']]
            ])->find();

            if ($existsSameName) {
                return '同一父级下已存在相同名称的角色: ' . $data['title'];
            }
        } else {
            // 新增时检查角色名称是否重复
            $existsSameName = Role::where([
                ['parent_id', '=', $data['parent_id']],
                ['title', '=', $data['title']]
            ])->find();

            if ($existsSameName) {
                return '同一父级下已存在相同名称的角色: ' . $data['title'];
            }
        }

        return true;
    }


    // 添加部门ID验证方法
    protected function isDeptIdValid($value, $rule, $data = [], $field = '', $title = '')
    {
        // 检查部门是否存在
        $targetDept = \app\model\api\admin\system\Dept::where([
            ['id', '=', $value],
        ])->find();

        if (!$targetDept) {
            return '所选部门不存在或已禁用';
        }

        return true;
    }
}
